package com.tian.netty.test;

import com.tian.netty.message.MsgType;
import com.tian.netty.test.charging.ChargingDataDto;
import com.tian.netty.test.charging.ChargingDataReq;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-05-13 22:07
 * {@code @version:} 1.0
 */
public class MyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //登录请求
        /*ChargerLoginDataReq req = new ChargerLoginDataReq(MsgType._0X_01);
        ChargerLoginMsg chargerLoginMsg = new ChargerLoginMsg();
        chargerLoginMsg.setGunNo("1000001");
        req.setResponseBody(chargerLoginMsg);*/

        //充电实时数据上报
        ChargingDataReq req = new ChargingDataReq(MsgType._0X_40);
        ChargingDataDto chargingDataDto=new ChargingDataDto();
        chargingDataDto.setUserId(1000001L);
        chargingDataDto.setGunNo("1000001");
        chargingDataDto.setChargingEndTime(new Date());
        chargingDataDto.setChargingStartTime(new Date());
        chargingDataDto.setChargingCount(new BigDecimal("100050"));
        req.setResponseBody(chargingDataDto);

        req.format();

        ByteBuf byteBufResp = Unpooled.copiedBuffer(req.getMsgObject());
        ctx.writeAndFlush(byteBufResp);

    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        System.out.println(new String(bytes, StandardCharsets.UTF_8));
    }
}
